var MAIN_TABLE = 'main-table';
var MAIN_FORM = 'main-form';

function openLayer(url, title, width, height) {
	title = title == null ? "" : title;
	width = width == null ? "70%" : width;
	height = height == null ? "70%" : height;
	layer.open({
		type : 2,
		title : title,
		closeBtn : 1,
		area : [ width, height ],
		maxmin : true,
		content : url,
		success : function(layero, index) {
			var body = layer.getChildFrame('body', index);
			var bodysize = $(body).height();
			var iframesize = $(layero).height();
			if (bodysize < iframesize) {
				layer.style(index, {
					height : (bodysize + 75) + 'px'
				});
			}
		}
	});
}

function addData(url, width, height) {
	openLayer(url, "新增", width, height);
}

function editData(url, id, width, height) {
	id = id == null ? "" : id;
	openLayer(url + "?id=" + id, "编辑", width, height);
}

function viewData(url, id, width, height) {
	id = id == null ? "" : id;
	openLayer(url + "?id=" + id + "&viewMode=1", "查看", width, height);
}

function formReset() {
	location.href = location.origin + location.pathname;
}

function deleteData(url, ids) {
	if (ids == null) {
		var selectData = layui.table.checkStatus(MAIN_TABLE).data;
		if (selectData.length == 0) {
			layer.alert("请勾选至少一条记录!", {
				icon : 2
			});
			return;
		} else {
			ids = "";
			for (var i = 0; i < selectData.length; i++) {
				ids += selectData[i].id + ",";
			}
		}
	}
	layer.confirm('确定删除吗?', {
		btn : [ '确定', '取消' ],
		icon : 0,
		title : '警告'
	}, function() {
		layer.msg('删除中', {
			icon : 16,
			shade : 0.7
		});
		$.post(url, {
			ids : ids
		}, function(data) {
			if (data.success) {
				layer.msg(data.msg, {
					icon : 1,
					time : 500
				}, function() {
					location.reload();
				});
			} else {
				layer.alert(data.msg, {
					icon : 2
				});
			}
		})
	}, function() {

	});
}

function postData(url,formid,sucCallBack,failCallBack){
	formid = formid == null ? "form" : "#"+formid;
	if(sucCallBack==null){
		sucCallBack=function(data){
			layer.msg(data.msg, {
				shade : 0.5,
				icon : 1,
				time : 1000
			}, function(){
				if (parent != self) {
					parent.location.reload();
				}
			});
		}
	}
	if(failCallBack==null){
		failCallBack=function(data){
			layer.alert(data.msg, {
				icon : 2
			});
		}
	}
	var shadeIndex = layer.msg('处理中', {
		icon : 16,
		shade : 0.5
	});
	$.post(url, $(formid).serialize(), function(data) {
		layer.close(shadeIndex);
		if (data.success) {
			sucCallBack(data);
		} else {
			failCallBack(data);
		}
	})
}
